﻿using ExcelUtil.Entity;
using Microsoft.Win32;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ExcelUtil
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private ExcelData excelData;
        private ExcelPackage package;
        private ExcelWorksheet worksheet;

        public MainWindow()
        {
            InitializeComponent();
            excelData = new ExcelData();
            excelData.FilePath = "请选择待分表";
            excelData.GeneratePath = "请选择储存路径";
            Binding binding = new Binding();//创建Binding实例
            binding.Source = excelData;//指定数据源
            binding.Path = new PropertyPath("FilePath");//指定访问路径 

            //使用Binding 连接数据源与Bingding目标
            BindingOperations.SetBinding(this.filePath, TextBox.TextProperty, binding);
            BindingOperations.SetBinding(this.generatePath, TextBox.TextProperty, new Binding
            {
                Source = excelData,
                Path = new PropertyPath("GeneratePath")
            });

        }

        private void ChooseExcel(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "所有Excel文件(*.xl;*.xlsx)|*.xl;*.xlsx";
            if (dialog.ShowDialog() == true)
            {
                excelData.FilePath = dialog.FileName;
                FileInfo directory = new FileInfo(excelData.FilePath);
                string fullName = directory.Directory.FullName;
                excelData.GeneratePath = fullName;
                GetExcelSheet();
            }
        }

        private void filePathChanged(object sender, TextChangedEventArgs e)
        {
            string result = ((TextBox)e.OriginalSource).Text;
            //MessageBox.Show(e.Message, "错误");
            excelData.FilePath = result;
        }
        /// <summary>
        /// 获得项目的根路径
        /// </summary>
        /// <returns></returns>
        public string GetProjectRootPath()
        {
            string rootPath = "";
            string BaseDirectoryPath = AppDomain.CurrentDomain.BaseDirectory; // F:\WAF Projects\mjl\code\HomeDecorationPSD\HomeDecorationPSD\bin\Debug\
                                                                              // 向上回退三级，才能到项目的根目录
            rootPath = BaseDirectoryPath.Substring(0, BaseDirectoryPath.LastIndexOf("\\")); // 第一个\是转义符，所以要写两个
            rootPath = rootPath.Substring(0, rootPath.LastIndexOf("\\"));
            rootPath = rootPath.Substring(0, rootPath.LastIndexOf("\\")); // F:\WAF Projects\mjl\code\HomeDecorationPSD\HomeDecorationPSD\
            return rootPath;
        }

        private void ChooseGenerateDir(object sender, RoutedEventArgs e)
        {
            string path = Util.openFileDialog(excelData.GeneratePath);
            if (!string.IsNullOrEmpty(path))
            {
                excelData.GeneratePath = path;
            }
        }

        private void generatePath_TextChanged(object sender, TextChangedEventArgs e)
        {
            string result = ((TextBox)e.OriginalSource).Text;
            excelData.GeneratePath = result;
        }

        private void ReadExcel(object sender, RoutedEventArgs e)
        {
            GetExcelSheet();
        }

        private void GetExcelSheet()
        {
            if (!File.Exists(excelData.FilePath))
            {
                MessageBox.Show("文件路劲错误!", "错误");
            }
            package = new ExcelPackage(new FileInfo(excelData.FilePath));

            var DataList = package.Workbook.Worksheets.Select(x => new Worksheet { Name = x.Name, Pos = x.Index }).ToList();
            this.sheetList.ItemsSource = DataList;//数据源
            this.sheetList.DisplayMemberPath = "Name";//sheet名称
            this.headerList.ItemsSource = null;//数据源
        }

        private void SheetSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((Selector)e.OriginalSource).SelectedValue != null)
            {
                string sheet = ((Worksheet)((Selector)e.OriginalSource).SelectedValue)?.Name;
                excelData.SheetName = sheet;
                worksheet = package.Workbook.Worksheets[sheet];
                excelData.endRow = worksheet.Dimension.End.Row;
                excelData.endCol = worksheet.Dimension.End.Column;
                List<ExcelHead> headList = new List<ExcelHead>();
                for (int i = 0; i < excelData.endCol; i++)
                {
                    ExcelRange range = worksheet.Cells[1, i + 1];
                    headList.Add(new ExcelHead { Header = range.Value?.ToString(), Pos = i + 1 });
                }
                this.headerList.ItemsSource = headList;//数据源
                this.headerList.DisplayMemberPath = "Header";//sheet名称
            }
        }

        private void HeaderSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((Selector)e.OriginalSource).SelectedValue == null) return;
            int colPos = ((ExcelHead)((Selector)e.OriginalSource).SelectedValue).Pos;//去重的列
            List<ClassData> dataList = new List<ClassData>();

            RowData headrowData = new RowData() { Index = 1 };
            List<ColData> headcolList = new List<ColData>();
            for (int col = 1; col <= excelData.endCol; col++)
            {
                headcolList.Add(new ColData() { Col = col, Value = worksheet.Cells[1, col].Value?.ToString() });

            }
            headrowData.Cols = headcolList;

            for (int row = 2; row <= excelData.endRow; row++)
            {
                string className = worksheet.Cells[row, colPos].Value?.ToString();
                ClassData classData = dataList.Find(x => x.ClassName == className);
                if (classData == null)
                {
                    classData = new ClassData(className);
                    classData.Rows.Add(headrowData);
                    dataList.Add(classData);
                }
                RowData rowData = new RowData() { Index = row };
                List<ColData> colList = new List<ColData>();
                for (int col = 1; col <= excelData.endCol; col++)
                {
                    colList.Add(new ColData() { Col = col, Value = worksheet.Cells[row, col].Value?.ToString() });

                }
                rowData.Cols = colList;
                classData.Rows.Add(rowData);
            }
            GenerateExcel(dataList);
        }
        private void GenerateExcel(List<ClassData> dataList)
        {
            if (!Directory.Exists(excelData.GeneratePath))
            {
                MessageBox.Show("生成文件保存路劲错误!", "错误");
            }
            foreach (var item in dataList)
            {
                using (var package = new ExcelPackage(new FileInfo($"{excelData.GeneratePath}/{item.ClassName}.xlsx")))
                {
                    var sheet = package.Workbook.Worksheets["Sheet1"];
                    if (sheet == null) sheet = package.Workbook.Worksheets.Add("Sheet1");
                    int hasRow = 0;
                    if (sheet.Dimension != null) hasRow = sheet.Dimension.End.Row;//已存在数据
                    for (int i = 1; i <= item.Rows.Count; i++)
                    {
                        if (i == 1 && hasRow > 0) continue;
                        RowData rowData = item.Rows[i - 1];
                        for (int j = 1; j <= rowData.Cols.Count; j++)
                        {
                            ColData colData = rowData.Cols[j - 1];
                            if (hasRow > 0)
                            {
                                sheet.Cells[(hasRow - 1) + i, j].Value = colData.Value;
                            }
                            else
                            {
                                sheet.Cells[i, j].Value = colData.Value;
                            }

                        }
                    }

                    //Save to file
                    package.Save();
                }
            }
            MessageBox.Show("生成成功!", "提示");
        }
    }

}
